<template>
  <div>
    <div class="all-wrap">
      <div class="all-title">视频管理</div>
      <div class="top-controllers" style="margin-bottom: 4px;">
        <el-select v-model="selectOwner" filterable clearable placeholder="选择歌手" style="width: 200px;margin-right: 20px;" @change="selectChange">
          <el-option v-for="item in singerList" :key="item.id" :label="item.singerName" :value="item.id" />
        </el-select>
        <el-input v-model="searchValue" clearable class="w-50 m-2" placeholder="请输入歌曲名称" @clear="inputClear"/>
        <el-button type="primary" @click="searchClick">搜索</el-button>
        <el-button type="primary" @click="addSingerFN">新增</el-button>
      </div>
    </div>
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column type="index" width="50" />
      <el-table-column prop="title" label="标题" width="250"> </el-table-column>
      <el-table-column prop="url" label="链接"  width="850"/>
      <el-table-column label="演唱者" width="100">
        <template #default="scope" >
          <el-tag v-if="scope.row.singer.id!=0" >{{ scope.row.singer.singerName }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="Controllers">
        <template #default="scope">
          <el-button type="primary" size="small" @click="editData(scope.row)">修改</el-button>
          <el-popconfirm width="220" confirm-button-text="OK" cancel-button-text="No, Thanks" :icon="InfoFilled"
            icon-color="#626AEF" title="Are you sure to delete this?" @confirm="confirmEvent(scope.row)">
            <template #reference>
              <el-button>Delete</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination v-model:current-page="currentPage" :page-size="10" layout="total, prev, pager, next" :total="dataTotal"
      @current-change="handleCurrentChange" />
    <el-dialog v-model="dialogSong" :title="popTitle">
      <el-form :model="form" ref="ruleFormRef" label-width="100" :rules="rules">
        <el-form-item label="视频名" prop="title">
          <el-input v-model="form.title" autocomplete="off" />
        </el-form-item>
        <el-form-item label="演唱者" prop="owner">
          <el-select v-model="form.owner" filterable placeholder="Select" style="width: 100%">
            <el-option v-for="item in singerList" :key="item.id" :label="item.singerName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="视频链接" prop="url">
        <!-- <el-upload
          ref="upload"
          class="upload-demo"
          action="/shopApi/admin/uploadVideo"
          :limit="1"
          :on-exceed="handleExceed"
          :on-success="uploadSuccess"
          :before-remove="beforeRemove"
          v-model:file-list="fileList"
          :auto-upload="true"
        >
          <template #trigger>
            <el-button type="primary">select file</el-button>
          </template>
          <template #tip>
            <div class="el-upload__tip text-red">
              限制上传一张，多上传会覆盖上一张
            </div>
            <div v-show="form.url">{{ form.url }}</div>
          </template>
        </el-upload> -->
        <el-input v-model="form.url" autocomplete="off" />
        &nbsp;
        <div class="upload_wrap" v-show="percentage<1">
          <input type="file" name="file" id="uploadVideo">
          <input type="button" value="开始上传" @click="uploadBiger">
        </div>
        <div class="loading"  style="width: 100%" v-show="percentage>1">
          <el-progress  :stroke-width="11" :percentage="percentage" />
        </div>
       </el-form-item>
        
      </el-form>
      <template #footer>
          <span class="dialog-footer">
            <el-button @click="cancelEdit">取消</el-button>
            <el-button type="primary" @click="submitEdit(ruleFormRef)">
              确定
            </el-button>
          </span>
        </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import axios from 'axios'
import {ref,reactive,onMounted} from 'vue'
import {ElMessage, FormInstance}from 'element-plus'
import { InfoFilled } from '@element-plus/icons-vue'
import { genFileId } from 'element-plus'
import type { UploadInstance, UploadProps, UploadRawFile } from 'element-plus'
import {getVideoList,addVideo,editVideo,deleteVideo,uploadBigVideo} from '../apis/video'
import {getSingerList} from '../apis/singer'
const ruleFormRef = ref<FormInstance>()
interface opytion {
  id: number
  singerName:string
}
const server=axios.create({
  baseURL:'/shopApi',
  timeout:50000,
  headers:{
    "Content-Type":'multipart/form-data',
    "Authorization":"Bearer "+sessionStorage.getItem("token")
  }
})
let singerList=ref<opytion[]>([])
let searchValue=ref('')
let selectOwner=ref('')
let tableData=ref([])
let currentPage=ref(1)
let dataTotal=ref(0)
let dialogSong=ref(false)
let popTitle=ref('新增数据')
let editId=ref(0)
let songer=ref(0)
let form=reactive({
  title:'',
  owner:'',
  url:''
})
let fileList=ref([])
let rules=reactive({
  title:[
    {min:2,max:38,message:"长度在2-18",trigger:'blur'},
    {required:true,trigger:'blur'}
  ],
  owner:[
  {required:true,trigger:'blur',message:"必填项"}
  ],
  url:[
  {required:true,trigger:'blur',message:"必填项",pattern:/http:|https:/}
  ],
})

const upload = ref<UploadInstance>()
const handleExceed: UploadProps['onExceed'] = (files) => {
  fileList.value=[]
  upload.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  upload.value!.handleStart(file)
}
const beforeRemove=(parmas)=>{
  form.url=""
}

const uploadSuccess=(res)=>{
  if(res.success!=true)return
  form.url=res.url
}
const cancelEdit=()=>{
  dialogSong.value=false
  fileList.value=[]
  resetForm()
}
const submitEdit=async(ruleFormRef)=>{
  await  ruleFormRef.validate(async(valid, fields) => {
    if(valid){
      if(popTitle.value=="新增数据"){
        let res=await addVideo(form)
        if(res.status==200){
          ElMessage({
            message: '新增歌手成功',
            type: 'success',
          })
          getDataList()
          dialogSong.value=false
          fileList.value=[]
          resetForm()
        }
      }else{
        let data={
          ...form,
          id:editId.value,
        }
        let res=await editVideo(data)
        if(res.status==200){
          ElMessage({
            message: '修改歌手成功',
            type: 'success',
          })
          getDataList()
          dialogSong.value=false
          fileList.value=[]
          resetForm()
        }
      }
    }
  })
}
const resetForm=()=>{
 let empty={}
 for(let i in form){
   empty[i]=''
 }
 Object.assign(form,empty)
 percentage.value=0
//  uploadVideo.value=""
}
const searchClick=()=>{
  getDataList()
}
const addSingerFN=()=>{
  popTitle.value="新增数据"
  dialogSong.value=true
}
const inputClear=()=>{
  currentPage.value=1
  getDataList()
}
const selectChange=()=>{
  getDataList()
}
const editData=(row)=>{
  popTitle.value="修改数据"
  editId.value=row.id
  form.title=row.title
  form.owner=row.singer.id
  form.url=row.url
  dialogSong.value=true
}
const confirmEvent=async(row)=>{
  let res=await deleteVideo({id:row.id})
  if(res.status==200){
    ElMessage({
      message: '删除视频成功',
      type: 'success',
    })
    getDataList()
  }
}
const handleCurrentChange=()=>{
  getDataList()
}
const getDataList=async()=>{
  let res=await getVideoList({id:selectOwner.value,page:currentPage.value,pageSize:10,title:searchValue.value})
  if(res.status==200){
    tableData.value=res.data.list
    dataTotal.value=res.data.total
  }
}
/**
 * 上传大文件
 */
let chunkSize = 1024 * 1024 * 3
let index=0
let size=0
let percentage=ref(0)
const uploadBiger=()=>{
  const uploadVideo=document.getElementById("uploadVideo") as HTMLInputElement
  if(uploadVideo==null) return
  let file=uploadVideo.files?.length?uploadVideo.files[0]:null
  if (file==null)return
  size=file.size
  let start = index * chunkSize
  let [fname, fext] = file.name.split(".")
  percentage.value=Math.floor((index/(size/chunkSize))*100)
  percentage.value=percentage.value>=100?100:percentage.value
  if (start > file.size) {
    mergeVideo(file.name)
    return
  }
  let blob = file.slice(start, (index+1) * chunkSize)
  let blobName = `${index}.${fext}`
  let blobFile = new File([blob], blobName)
  let formData = new FormData()
  formData.append("file", blobFile)
  formData.append("name", fname)
  index++
  server.post("/admin/uploadVideo",formData).then(res=>{
    if(res.status==200){
      uploadBiger()
    }
  })
  
}
const mergeVideo=(fileName)=>{
  let data={
    fileName
  }
  server.post("/admin/mergeVideo",data).then(res=>{
    if(res.status==200){
      form.url=res.data.url
    }
  })
}
onMounted(()=>{
  getDataList()
  getSingerList({pageSize:99999}).then(res=>{
    if(res.status==200){
      singerList.value=res.data.list
    }
  })
})
</script>
<style lang="less" scoped>
  .top-controllers {
  width: 100%;
  height: 30px;

  .w-50 {
    width: 200px;
    margin-right: 20px;
  }
}
</style>